package com.yanqu.road.server.manger.activity.twins;

import com.yanqu.road.entity.activity.twins.config.TwinsPvpConfig;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.TwinsProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.twins.TwinsModule;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//调试
public class TwinsDebugMgr extends TempMgr {

    private static RandomHelper randomHelper = new RandomHelper();

    public static RandomHelper getRandomHelper() {
        return randomHelper;
    }

    public static void setRandomHelper(RandomHelper randomHelper) {
        TwinsDebugMgr.randomHelper = randomHelper;
    }

    private static List<Long> goRoomList = new ArrayList<>();

    private static List<Long> onlineUserList = new ArrayList<>();

    //登录时间间隔
    private static long loginCutTime;

    private static long checkRoomUser;


    private static List<Long> debugUserIdList = new ArrayList<>();

    public static void pvpDebug(String userCount,String bool,String attack,String attBossCount,String attUserId,String attUserCount){
        int num = Integer.valueOf(userCount);
        List<UserInfo> canGoList = new ArrayList<>();
        List<UserInfo> userInfoList = UserMgr.getUserInfoList();
        for(UserInfo userInfo : userInfoList){
            if(canGoList.size() > num){
                break;
            }
            if(userInfo.getTitleId() > 10 && GamePlayerMgr.getOnlinePlayer(userInfo.getUserId()) == null){
                if(!canGoList.contains(userInfo)){
                    canGoList.add(userInfo);
                }
            }
        }
        TwinsProto.CrossTwinsPvpDebugUserReqMsg.Builder reqMsg = TwinsProto.CrossTwinsPvpDebugUserReqMsg.newBuilder();
        reqMsg.setActivityId(TwinsMgr.getActivityId());
        reqMsg.setAttBossCount(Integer.valueOf(attBossCount));
        reqMsg.setAttUserId(Long.valueOf(attUserId));
        reqMsg.setAttUserCount(Integer.valueOf(attUserCount));
        for(UserInfo userInfo : canGoList){
            TwinsProto.CrossTwinsPvpUpdateUserMsg.Builder userMsg = TwinsProto.CrossTwinsPvpUpdateUserMsg.newBuilder();
            userMsg.setUserId(userInfo.getUserId());
            userMsg.setBool(bool);
            userMsg.setAttack(attack);
            UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(userInfo.getUserId(), GameServer.getInstance().getServerId());
            if(userBaseInfo != null){
                userMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            }
            reqMsg.addUser(userMsg);
            if(!debugUserIdList.contains(userInfo.getUserId())){
                debugUserIdList.add(userInfo.getUserId());
            }
        }
        getLogger().error("发送了{}个玩家上去",canGoList.size());
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(CrossProtocol.C2_CROSS_TWINS_PVP_DEBUG, reqMsg);
        GamePlayerMgr.sendPacket(0, pbMsg);
    }

    public static void timerTask(){
        if(GameServer.getInstance().getServerId() != 888821){
            return;
        }
        checkOnline();
        goRoom();
        online();

        long nowTime = System.currentTimeMillis();
        if(nowTime - checkRoomUser > 20 * DateHelper.SECOND_MILLIONS){
            checkOutRoom();
            checkRoomUser = nowTime;
        }

    }

    private static void checkOnline(){
        List<Long> removeUserIdList = new ArrayList<>();
        for(long userId : onlineUserList){
            GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if(gamePlayer == null){
                removeUserIdList.add(userId);
            }else{
                gamePlayer.setLastPingTime(System.currentTimeMillis());
            }
        }
        for(long userId : removeUserIdList){
            onlineUserList.remove(userId);
            goRoomList.remove(userId);
        }
    }

    private static void online(){
        long nowTime = System.currentTimeMillis();
        //5秒登录一个
        if(nowTime - loginCutTime < DateHelper.SECOND_MILLIONS){
            return;
        }
        getLogger().error("{}个用户在线",onlineUserList.size());
        loginCutTime = nowTime;
        int maxCount = 1;
        int userCount = 1;
        if(onlineUserList.size() > maxCount){
            return;
        }
        List<UserInfo> userInfoList = UserMgr.getUserInfoList();
        if(userInfoList.size() == 0){
            return;
        }
        long startTime = System.currentTimeMillis();
        while (userCount > 0){
            int userIndex = randomHelper.next(0,userInfoList.size());
            UserInfo userInfo = userInfoList.get(userIndex);
            if(!onlineUserList.contains(userInfo.getUserId()) && userInfo.getTitleId() > 10){
                GamePlayer player = GamePlayerMgr.getPlayer(userInfo.getUserId());
                if(player != null){
                    TwinsProto.TwinsPvpGetRewardReqMsg.Builder loginMsg = TwinsProto.TwinsPvpGetRewardReqMsg.newBuilder();
                    loginMsg.setActivityId(TwinsMgr.getActivityId());
                    player.sendPacket(Protocol.S_PLAYER_LOGIN, loginMsg);
                    onlineUserList.add(userInfo.getUserId());
                }
            }
            userCount--;
        }
        long endTime = System.currentTimeMillis();
//        getLogger().error("拉取{}个用户消耗{}ms",userCount,endTime - startTime);
    }

    private static void goRoom(){
        for(long userId : onlineUserList){
            if(!goRoomList.contains(userId)){
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                if(player != null){
                    TwinsProto.TwinsPvpEnterBossReqMsg.Builder reqMsg = TwinsProto.TwinsPvpEnterBossReqMsg.newBuilder();
                    reqMsg.setActivityId(TwinsMgr.getActivityId());
                    List<TwinsPvpConfig> bossList = new ArrayList<>(TwinsMgr.getConfig().getPvpConfigMap().values());
                    reqMsg.setBossId(bossList.get(randomHelper.next(0,bossList.size())).getId());
                    player.sendPacket(Protocol.S_TWINS_PVP_ENTER_BOSS, reqMsg);
                    getLogger().error("{}进入房间10001",userId);
                    goRoomList.add(userId);
                }
            }
        }
    }

    public static void removeRoom(long userId){
        goRoomList.remove(userId);
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        if(player != null){
            TwinsProto.TwinsPvpLeaveBossRespMsg.Builder reqMsg = TwinsProto.TwinsPvpLeaveBossRespMsg.newBuilder();
            reqMsg.setRet(0);
            player.sendPacket(Protocol.U_TWINS_PVP_LEAVE_BOSS, reqMsg);
        }
    }

    public static void checkOutRoom(){
        for(long userId : goRoomList){
            GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if(gamePlayer != null){
                gamePlayer.getModule(TwinsModule.class).syncUserData();
            }
        }
    }

    public static void clearEnterRoom() {
        for(long userId : goRoomList){
            GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if(gamePlayer != null){
                gamePlayer.getModule(TwinsModule.class).afterLogin();
            }
        }
        goRoomList = new ArrayList<>();
    }

    public static boolean isDebugUser(long userId) {
        return debugUserIdList.contains(userId);
    }

    public static boolean removeDebugUser(long userId) {
        return debugUserIdList.remove(userId);
    }

    //把玩家商会的人送上去打boss selfUnion,10004
    public static void sendUnionMember(long userId,int bossId) {
        List<UserInfo> canGoList = new ArrayList<>();
        List<Integer> bossIdList = new ArrayList<>(TwinsMgr.getConfig().getPvpConfigMap().keySet());
        if(!bossIdList.contains(bossId)){
            return;
        }
        UserInfo selfUserInfo = UserMgr.getUserInfo(userId);
        if(selfUserInfo != null && !StringUtils.isNullOrEmpty(selfUserInfo.getUnionUid())){
            Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(selfUserInfo.getUnionUid());
            for(CrossUnionMember member : memberMap.values()){
                if(member.getUserId() == userId)continue;
                UserInfo userInfo = UserMgr.getUserInfo(member.getUserId());
                //其他区服的就没了？
                if(userInfo != null && !onlineUserList.contains(userInfo.getUserId()) && userInfo.getTitleId() > 10){
                    canGoList.add(userInfo);
                }
            }
        }
        String bool = "40000";
        String attack = "1000";
        int activityId = TwinsMgr.getActivityId();
        TwinsProto.CrossTwinsPvpDebugUserReqMsg.Builder reqMsg = TwinsProto.CrossTwinsPvpDebugUserReqMsg.newBuilder();
        reqMsg.setActivityId(TwinsMgr.getActivityId());
        reqMsg.setBossId(bossId);
        reqMsg.setAttBossCount(0);
        reqMsg.setAttUserId(1);
        reqMsg.setAttUserCount(0);
        for(UserInfo userInfo : canGoList){
            TwinsProto.CrossTwinsPvpUpdateUserMsg.Builder userMsg = TwinsProto.CrossTwinsPvpUpdateUserMsg.newBuilder();
            userMsg.setUserId(userInfo.getUserId());
            userMsg.setBool(bool);
            userMsg.setAttack(attack);
            UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(userInfo.getUserId(), GameServer.getInstance().getServerId());
            if(userBaseInfo != null){
                userMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            }
            reqMsg.addUser(userMsg);
            if(!debugUserIdList.contains(userInfo.getUserId())){
                debugUserIdList.add(userInfo.getUserId());
            }
        }
        getLogger().error("发送了{}个玩家上去",canGoList.size());
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, userId);


        GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_TWINS_PVP_DEBUG,reqMsg,0,activityId,groupId);

    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean save() {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }


}
